<template>
  <div id="app">
    <AppNavbar />

    <div class="job-list-container">
      <div class="header">
        <h1>职位列表</h1>
        <!-- 添加我的收藏按钮 -->
        <button
          v-if="isCandidate"
          class="favorite-btn"
          @click="viewMyFavorites"
        >
          我的收藏
        </button>
      </div>

      <!-- 筛选区域 -->
      <div class="filter-container">
        <div class="filter-row">
          <div class="filter-item">
            <label for="positionName">职位名称</label>
            <input
              id="positionName"
              v-model="searchParams.positionName"
              type="text"
              placeholder="请输入职位名称"
              class="filter-input"
            />
          </div>

          <div class="filter-item">
            <label for="positionType">职位类型</label>
            <select
              id="positionType"
              v-model="searchParams.positionType"
              class="filter-select"
            >
              <option value="">全部</option>
              <option value="full-time">全职</option>
              <option value="part-time">兼职</option>
              <option value="internship">实习</option>
            </select>
          </div>

          <div class="filter-item">
            <label for="province">省份</label>
            <select
              id="province"
              v-model="searchParams.province"
              class="filter-select"
            >
              <option value="">全部</option>
              <option
                v-for="province in provinceList"
                :key="province"
                :value="province"
              >
                {{ province }}
              </option>
            </select>
          </div>

          <div class="filter-item">
            <label for="tagName">技能标签</label>
            <div class="tag-dropdown-container">
              <select
                v-model="selectedCategory"
                class="filter-select category-select"
              >
                <option value="">选择分类</option>
                <option
                  v-for="(tags, category) in tagList"
                  :key="category"
                  :value="category"
                >
                  {{ category }}
                </option>
              </select>
              <select
                v-model="searchParams.tagName"
                :disabled="!selectedCategory"
                class="filter-select tag-select"
              >
                <option value="">选择标签</option>
                <option
                  v-for="tag in tagList[selectedCategory]"
                  :key="tag"
                  :value="tag"
                >
                  {{ tag }}
                </option>
              </select>
            </div>
          </div>

          <div class="filter-buttons">
            <button class="search-btn" @click="searchJobs">搜索</button>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </div>
        </div>
      </div>

      <!-- 职位列表 -->
      <div
        class="job-list"
        ref="jobListContainer"
        @scroll="handleScroll"
      >
        <div
          v-for="job in jobList"
          :key="job.positionId"
          class="job-item"
        >
          <!-- 左侧内容：职位名称和标签 -->
          <div class="job-left-content">
            <div class="job-header">
              <h2 class="job-title">{{ job.positionName }}</h2>
              <span class="position-type">{{ getPositionTypeText(job.positionType) }}</span>
              <!-- 添加状态标签 -->
              <span
                :class="['status-tag', { 'status-active': job.status === '1', 'status-inactive': job.status === '0' }]"
              >
                {{ getJobStatusText(job.status) }}
              </span>
            </div>

            <!-- 将省份标签与技能标签放在同一行 -->
            <div class="job-tags-container">
              <div class="job-tags" v-if="job.tagList && job.tagList.length > 0">
                <span
                  v-for="(tag, index) in job.tagList"
                  :key="index"
                  class="tag"
                >
                  {{ tag }}
                </span>
              </div>

              <!-- 省份标签紧贴在技能标签右边 -->
              <div class="job-location" v-if="job.province">
                <span class="location-tag">{{ job.province }}</span>
              </div>
            </div>
          </div>

          <!-- 右侧操作区域 -->
          <div class="job-right-content">
            <span class="salary-text">{{ job.salaryRange }}</span>
            <div class="job-actions">
              <button
                class="detail-btn"
                @click="viewJobDetail(job.positionId, job.status)"
              >
                查看详情
              </button>
            </div>
          </div>
        </div>

        <!-- 加载更多提示 -->
        <div v-if="loadingMore" class="loading-more">
          加载中...
        </div>

        <div v-if="jobList.length === 0 && !loadingMore" class="empty-state">
          <p>暂无符合条件的职位</p>
        </div>

        <div v-if="noMoreData && jobList.length > 0" class="no-more-data">
          没有更多数据了
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppNavbar from '../components/AppNavbar.vue'
import apiClient from '../utils/api.js'

export default {
  name: 'JobListView',
  components: {
    AppNavbar
  },
  setup () {
    const jobList = ref([])
    const tagList = ref({})
    const selectedCategory = ref('')
    const route = useRoute()
    const router = useRouter()
    const isCandidate = ref(false)
    const loadingMore = ref(false)
    const noMoreData = ref(false)
    const jobListContainer = ref(null)

    // 定义省份列表（存储在前端）
    const provinceList = [
      '北京市', '上海市', '天津市', '重庆市',
      '河北省', '山西省', '辽宁省', '吉林省', '黑龙江省',
      '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省',
      '河南省', '湖北省', '湖南省', '广东省', '海南省',
      '四川省', '贵州省', '云南省', '陕西省', '甘肃省',
      '青海省', '台湾省',
      '内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区',
      '香港特别行政区', '澳门特别行政区'
    ]

    const searchParams = ref({
      positionName: '',
      positionType: '',
      tagName: '',
      province: ''
    })

    // 检查用户类型
    const checkUserType = () => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr)
        isCandidate.value = userInfo.userType === 'candidate'
      }
    }

    onMounted(() => {
      checkUserType()
      fetchTagList()

      // 检查路由参数，如果有tagName则设置搜索条件
      if (route.query.tagName) {
        searchParams.value.tagName = route.query.tagName
        // 尝试找到标签对应的分类
        findCategoryByTag(route.query.tagName)
      }

      fetchJobList()

      // 添加滚动事件监听
      nextTick(() => {
        if (jobListContainer.value) {
          jobListContainer.value.addEventListener('scroll', handleScroll)
        }
      })
    })

    // 监听路由变化
    watch(() => route.query, (newQuery) => {
      if (newQuery.tagName) {
        searchParams.value.tagName = newQuery.tagName
        findCategoryByTag(newQuery.tagName)
        fetchJobList()
      }
    })

    const findCategoryByTag = (tag) => {
      for (const [category, tags] of Object.entries(tagList.value)) {
        if (tags.includes(tag)) {
          selectedCategory.value = category
          break
        }
      }
    }

    const fetchTagList = async () => {
      try {
        const response = await apiClient.get('/job/tagList')
        if (response.data.code === '200') {
          tagList.value = response.data.data
        } else {
          console.error('获取标签列表失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求标签列表出错:', error)
      }
    }

    const fetchJobList = async (isLoadMore = false) => {
      // 如果是加载更多且已经没有更多数据，则直接返回
      if (isLoadMore && noMoreData.value) return

      try {
        // 设置加载状态
        if (isLoadMore) {
          loadingMore.value = true
        }

        const params = {
          positionName: searchParams.value.positionName || null,
          positionType: searchParams.value.positionType || null,
          tagName: searchParams.value.tagName || null,
          province: searchParams.value.province || null,
          offset: isLoadMore ? jobList.value.length : 0 // 添加offset参数
        }

        const response = await apiClient.post('/job/jobList', params)

        if (response.data.code === '200') {
          if (isLoadMore) {
            // 如果是加载更多，将新数据追加到现有数据后面
            if (response.data.data.length > 0) {
              jobList.value = [...jobList.value, ...response.data.data]
            } else {
              // 如果没有更多数据，设置标志位
              noMoreData.value = true
            }
          } else {
            // 如果是刷新数据，直接替换
            jobList.value = response.data.data
            noMoreData.value = false // 重置无更多数据标志
          }
        } else {
          console.error('获取岗位列表失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求出错:', error)
      } finally {
        if (isLoadMore) {
          loadingMore.value = false
        }
      }
    }

    // 获取我的收藏职位列表
    const fetchFavoriteJobs = async () => {
      try {
        const response = await apiClient.get('/candidate/getCollectSimpleJobList')

        if (response.data.code === '200') {
          jobList.value = response.data.data
        } else {
          console.error('获取收藏职位列表失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求收藏职位列表出错:', error)
      }
    }

    const getPositionTypeText = (type) => {
      const typeMap = {
        'full-time': '全职',
        'part-time': '兼职',
        internship: '实习'
      }
      return typeMap[type] || type
    }

    // 获取职位状态文本
    const getJobStatusText = (status) => {
      const statusMap = {
        1: '招聘中',
        0: '已停招'
      }
      return statusMap[status] || '未知状态'
    }

    const searchJobs = () => {
      // 搜索时重置分页状态
      noMoreData.value = false
      fetchJobList()
    }

    const resetFilters = () => {
      searchParams.value = {
        positionName: '',
        positionType: '',
        tagName: '',
        province: ''
      }
      selectedCategory.value = ''
      noMoreData.value = false
      fetchJobList()
    }

    const viewJobDetail = (positionId, status) => {
      router.push({
        path: `/job/detail/${positionId}`,
        query: { status: status }
      })
    }

    // 查看我的收藏
    const viewMyFavorites = () => {
      // 查看收藏时重置分页状态
      noMoreData.value = false
      fetchFavoriteJobs()
    }

    // 处理滚动事件
    const handleScroll = () => {
      if (!jobListContainer.value || loadingMore.value || noMoreData.value) return

      const { scrollTop, scrollHeight, clientHeight } = jobListContainer.value
      // 当滚动到底部附近时加载更多
      if (scrollTop + clientHeight >= scrollHeight - 10) {
        fetchJobList(true) // 加载更多数据
      }
    }

    return {
      jobList,
      tagList,
      provinceList,
      selectedCategory,
      searchParams,
      isCandidate,
      loadingMore,
      noMoreData,
      jobListContainer,
      getPositionTypeText,
      getJobStatusText,
      searchJobs,
      resetFilters,
      viewJobDetail,
      viewMyFavorites,
      handleScroll
    }
  }
}
</script>

<style scoped>
#app {
  background: linear-gradient(to right, #e0f7fa, #ffffff);
  min-height: 100vh;
  padding: 20px;
}

.job-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.header h1 {
  color: #1890ff;
  margin: 0;
}

/* 我的收藏按钮样式 */
.favorite-btn {
  background-color: #ffcc00;
  color: #333;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.favorite-btn:hover {
  background-color: #ffd740;
}

.filter-container {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: end;
}

.filter-item {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 150px;
}

.filter-item label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.filter-input,
.filter-select {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.filter-input:focus,
.filter-select:focus {
  border-color: #1890ff;
  outline: 0;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.tag-dropdown-container {
  display: flex;
  gap: 10px;
}

.category-select,
.tag-select {
  flex: 1;
}

.filter-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 1px;
}

.search-btn,
.reset-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  white-space: nowrap;
}

.search-btn {
  background-color: #1890ff;
  color: white;
  border: 1px solid #1890ff;
}

.search-btn:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.reset-btn {
  background-color: #fff;
  color: #1890ff;
  border: 1px solid #1890ff;
}

.reset-btn:hover {
  background-color: #e6f7ff;
}

.job-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-height: calc(100vh - 250px);
  overflow-y: auto;
  padding: 10px;
}

.job-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s;
}

.job-item:hover {
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

.job-left-content {
  flex-grow: 1;
  margin-right: 20px;
}

.job-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.job-title {
  margin: 0;
  color: #333;
  font-size: 18px;
  flex-grow: 0;
}

.position-type {
  margin-left: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  background-color: #f9f0ff;
  color: #722ed1;
  white-space: nowrap;
}

/* 职位状态标签样式 */
.status-tag {
  margin-left: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-inactive {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

/* 调整标签容器为flex布局 */
.job-tags-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 调整省份标签样式 */
.location-tag {
  background-color: #fffbe6;
  color: #fa8c16;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  border: 1px solid #ffe58f;
}

.job-right-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.salary-text {
  font-size: 16px;
  font-weight: 500;
  color: #1890ff;
  white-space: nowrap;
}

.job-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.detail-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  white-space: nowrap;
  background-color: #1890ff;
  color: white;
  border: 1px solid #1890ff;
}

.detail-btn:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.empty-state {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  color: #999;
}

.loading-more,
.no-more-data {
  text-align: center;
  padding: 20px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-item {
    min-width: auto;
  }

  .job-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .job-right-content {
    width: 100%;
    justify-content: space-between;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #eee;
  }
}
</style>
